package megrez.bussiness.schedule.entity;

import static org.springframework.util.StringUtils.hasText;

import java.time.Instant;

import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.PrePersist;
import javax.persistence.Table;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import megrez.common.jpa.AbstractIdEntity;
import megrez.common.util.StringHelper;

/**
 * 任务日志
 *  
 * @author Lucky Yang
 * @since 0.0.1
 */
@Entity
@Getter
@Setter
@ToString
@Table(name = "job_log")
public class JobLog extends AbstractIdEntity {
    public static enum Level {
        /** 已启动*/
        STARTED,
        /** 运行 */
        RUNNING,
        /** 错误 */
        ERROR,
        /** 完成 */
        COMPLETE,
        /** 已停止 */
        STOPPED;
    }

    @ManyToOne
    @JoinColumn(name = "jobId")
    private Job job;

    /** 日志时间 */
    private Instant createTime;

    /** 信息等级 */
    @Enumerated(EnumType.STRING)
    private Level level;

    /** 消息 */
    private String message;

    /** 耗时：毫秒 */
    private Long costTime;

    public JobLog() {
    }

    public JobLog(Job job, Level level, String message) {
        this.job = job;
        this.level = level;
        if(hasText(message)) {
            this.message = StringHelper.limitLength(message, 999);
        }
    }
 
    public JobLog(Job jobInfo, Level level, String message, Long costTime) {
        this(jobInfo, level, message);
        this.costTime = costTime;
    }

    @PrePersist
    public void preAction() {
        if (this.createTime == null) {
            this.createTime = Instant.now();
        }
    }
}
